package utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class StringUtils {


	public static String replicate(int nTimes, String text) {
		String s = "";
		for (int i = 0; i < nTimes; i++) {
			s = s + text;
		}
		return s;
	}

	public static String isNull(String text, String ifNull) {
		return text == null ? ifNull : text;
	}

	// public static String isNull(Object obj, String ifNull, String ifNotNull){
	// return obj==null ? ifNull : ifNotNull;
	// }

	public static String isNull(Object obj, String ifNull, String fieldName) throws Exception {
		String s = ifNull;
		if (obj != null) {
			Class<?> c = obj.getClass();
			System.out.println("CLASE:" + c.getName());
			Field t = ReflectionUtils.findField(c, fieldName);
			try {
				s = (String) t.get(obj);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return s;

	}

	/**
	 * Return an array of String of an string with line separators
	 * 
	 * @param str
	 *            to split
	 * @param skipWhiteLines
	 *            if wanted
	 * @return
	 */
	public static String[] SplitLines(String str, boolean skipWhiteLines) {
		if (!skipWhiteLines)
			return str.split("\r?\n|\r");
		else
			return str.split("[\r?\n|\r]+");
	}

	/**
	 * Return an array of strings after removing comments
	 * 
	 * @param str
	 * @param skipWhiteLines
	 * @param commentStr
	 * @return
	 */
	public static String[] SplitLinesAndRemoveComments(String str,
			boolean skipWhiteLines, String commentStr) {
		List<String> lstStr = new ArrayList<String>();
		for (String s : SplitLines(str, skipWhiteLines)) {
			int offset = s.indexOf(commentStr);

			if (-1 != offset)
				s = s.substring(0, offset);
			if (!skipWhiteLines || s.trim().length() > 0)
				lstStr.add(s);

		}
		return lstStr.toArray(new String[0]);
	}

	public static String getSimpleClassName(String canonicalClassName) {

		return getLastSplit(canonicalClassName, ".");

	}

	public static String getLastSplit(String string, String separator) {

		return string.substring(string.lastIndexOf(separator)
				+ separator.length());

	}

	public static String removeJavaComments(String lines) {
		return lines.replaceAll(
				"(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)", "");
	}


}
